package com.itheima.controller;

import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Select;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Component
@Aspect
public class Test {
//    @Pointcut("execution(* com.itheima.service.impl.*.save(..))")
//    public void abc(){
//
//    }
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.itheima.aspact.RecordTimeAnno)")

    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {


        long begin = System.currentTimeMillis();

        OperateLog operateLog = new OperateLog();

        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());

        Object result = joinPoint.proceed();

        long end = System.currentTimeMillis();

        if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0 ) {
            operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        }

        operateLog.setReturnValue(result != null ? result.toString() : "");
        operateLog.setCostTime((end - begin))  ;

        operateLog.setOperateEmpId(getCurrentUserId());
        operateLogMapper.insert(operateLog);

        return result;
    }
    private Integer getCurrentUserId(){
        System.out.println("当前用户的id"+CurrentHolder.getUserId());
        return CurrentHolder.getUserId();
    }

}
